<?
 
require_once("mysql.php");
require_once("utilities.php");
 
/*
 * Input - what we got from a google place details search 
 * Output - location string ("San Francisco, CA"); 
 */
function get_location_from_google_place_details($details) {

    $loc = "";

    if (strtolower(@$details['status']) != "ok") {
        return NULL;
    }

    $address_components = $details['result']['address_components'];

    if (count($address_components) < 3) {
        return NULL;
    }

    foreach($address_components as $component) {

        if ($component['types'][0] == "locality") {
            $loc = $loc.$component['long_name'];
        }

        if ($component['types'][0] == "administrative_area_level_1") {
            $loc = $loc.", ".$component['short_name'];
        }

        if ($component['types'][0] == "country" && $component['short_name'] != "US") {
            $loc = $loc.", ".$component['short_name'];
        }
    }
 
    return (strtolower($loc));

}

function get_google_place_details($gref) {

    $APPKEY = "AIzaSyBQZ7w1bdCtYlJ1XYHCw6CWhuwUybKs6fs";
    $SEARCH = "https://maps.googleapis.com/maps/api/place/details/json?reference=".$gref."&sensor=true&key=".$APPKEY;

    return file_get_contents($SEARCH);
}

function find_or_create_reference($gid, $gref) {

    $r = MYSQL_Q("SELECT * FROM reference WHERE gid='".$gid."'");
    $c = mysql_num_rows($r);
    $loc = NULL;

    if ($c == 0) {

        // Didn't find it in our local cache. Search it in Google

        $json = get_google_place_details($gref);

        if (trim($json) == "") {
            return NULL;
        }

        $details = @json_decode($json, true);

        $loc = get_location_from_google_place_details($details);
    
        if ($loc == NULL) {
            //return NULL;
        }

        MYSQL_Q("INSERT INTO reference VALUES ('".$gid."', '".$gref."', '".ESC($json)."', 1)");
 
    } else {

        $row = mysql_fetch_assoc($r);

        $json = stripslashes($row['details']);

        if (trim($json) == "") {
            /*
             * Should never happen, except for the legacy entries where we didn't store the google results
             */
            $json = get_google_place_details($gref);

            if (trim($json) == "") {
                return NULL;
            }

            MYSQL_Q("UPDATE reference SET details='".ESC($json)."' WHERE gid='".$gid."'");
        }

        $details = @json_decode($json, true);

        $loc = get_location_from_google_place_details($details);

        if ($loc == NULL) {
            //return NULL;
        }

        MYSQL_Q("UPDATE reference SET count=".($row['count']+1)." WHERE gid='".$gid."'");
    }

    return array('gid' => $gid, 'gref' => $gref, 'location' => $loc);
}

 
?>